package com.co0964.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public final class JdbcUtil {
	
	//连接数据库的参数
	public static String url = null;
	public static String user = null;
	public static String driver = null;
	private static String password = null;
	
	public static ThreadLocal<Connection> container = new ThreadLocal<Connection>();
	
	private JdbcUtil () {}
	
	/**
	 * 初始化
	 * @return
	 */
	public static boolean init(){
		try{
			url = Configuration.getString("db.url");
			user = Configuration.getString("db.user");
			password = Configuration.getString("db.password");
			driver = Configuration.getString("db.driver");
			Class.forName(driver); //加载驱动
			return true;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 获得连接
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		Connection conn = container.get();//获取当前线程的连接
		if(null != conn){
			return conn;
		}
		return DriverManager.getConnection(url, user, password); //创建一个新连接
	}
	
	/**
	*开启事务
	*/
	public static void startTransaction(){
		try{
			Connection conn = getConnection();//获取连接
			container.set(conn);//将此连接放在当前线程上
			conn.setAutoCommit(false);//开启事务
		}catch(SQLException e){
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	/**
	*提交事务
	*/
	public static void commit(){
		try{
			Connection conn = container.get();//从当前线程上获取连接
			if(null != conn){//如果连接为空，则不做处理
				conn.commit();//提交事务
			}
		}catch(SQLException e){
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	/**
	*回滚事务
	*/
	public static void rollback(){
		try{
			Connection conn = container.get();//检查当前线程是否存在连接
			if(null != conn){
				conn.rollback();//回滚事务
			}
		}catch(SQLException e){
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	/**
	*关闭连接
	*/
	public static void close(){
		try{
			Connection conn = container.get();
			if(null != conn){
				conn.close();
			}
		}catch(SQLException e){
			throw new RuntimeException(e.getMessage(), e);
		}finally{
			container.remove();//从当前线程移除连接切记
		}
	}
	
}